<template>
	<view>
		<image @touchstart="startRecognize" @touchend="endRecognize" class="voice" mode="aspectFill"
			src="../../../static/ai/voice.png"></image>
		<view v-if="toast" class="toast">
			{{toast}}
			<u-line-progress :percentage="volume" height="2" :showText="false"></u-line-progress>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				id: null,
				speechId: null,
				text: '',
				toast: 'toasttoast',
				volume: 0,
				startTime: 0
			}
		},
		mounted() {
			this.id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
				const r = Math.random() * 16 | 0
				const v = c === 'x' ? r : (r & 0x3 | 0x8)
				return v.toString(16)
			})
			plus.speech.addEventListener('start', this.ontStart, false)
			plus.speech.addEventListener('recognition', this.onRecognition, false)
			plus.speech.addEventListener('end', this.onEnd, false)
			plus.speech.addEventListener('volumeChange', this.onVolumeChange, false)
		},
		methods: {
			ontStart() {
				if (this.speechId != this.id) {
					return
				}
				this.toast = '聆听中,请按住不动大声说,说完等待3~5秒...'
			},
			onVolumeChange(e) {
				this.volume = 100 * e.volume 
				console.log('Event: volumeChange ', this.volume)
			},
			onRecognition(e) {
				if (this.speechId != this.id) {
					return
				}
				this.text += e.result
				this.text ? (this.text += '\n') : this.text = ''
				this.toast = this.text
			},
			onEnd() {
				if (this.speechId != this.id) {
					return
				}
				this.toast = ''
				const isTouch = (Date.now() - this.startTime) > 500
				if (!this.text) {
					plus.nativeUI.toast(isTouch ? '没有听清您在说什么' : '按住按钮对我说')
				} else {
					this.$emit('recognize', this.text)
					this.text = ''
				}
				this.volume = 0
			},
			startRecognize() {
				this.speechId = this.id
				this.startTime = Date.now()
				plus.speech.startRecognize({
					engine: 'baidu',
					lang: 'zh-cn',
					userInterface: false,
					continue: true
				})
			},
			endRecognize() {
				plus.speech.stopRecognize()
			}
		}
	}
</script>

<style lang="scss">
	.voice {
		width: 32rpx;
		height: 32rpx;
		margin-right: 8rpx;
	}

	.toast {
		position: absolute;
		top: 48%;
		left: 48%;
		background-color: rgba(0, 0, 0, .8);
		padding: 16rpx 24rpx;
		color: #ffffff;
		border-radius: 6rpx;
	}
</style>